package com.example.travelexpensemanager;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class ChooseAccount extends Activity {

	Spinner spnChooseAccount;
	Button btnOpenAccount, openAccountstatistics, deleteAccount,
			btnEditAccount, btnRenameAccount;
	DatabaseOperations databaseOperations;
	ArrayAdapter<String> adapter;
	ArrayList<String> titles;
	EditText input;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Code to link to the layout */
		setContentView(R.layout.choose_account);

		/* To create an object of titles */
		titles = new ArrayList<String>();

		/* Creating object to access its methods */
		databaseOperations = new DatabaseOperations(getApplicationContext());

		/* Code to open the database */
		databaseOperations.openWriteableDatabase();

		/* Code to get all the accounts from the database */
		titles = databaseOperations.retrieveAll(
				DatabaseOperations.getAmounttable(),
				new String[] { DatabaseOperations.getAmounttabletitle() },
				null, null, null, null, null);

		/* Code to close the database */
		databaseOperations.closeDatabase();

		if (titles.size() == 0) {
			Toast.makeText(getApplicationContext(), "No Account to open",
					Toast.LENGTH_SHORT).show();
			finish();
		}

		/* Initialising the adapter */
		adapter = new ArrayAdapter<String>(getApplicationContext(),
				android.R.layout.simple_spinner_item, titles);

		/* Initialising the spinner object */
		spnChooseAccount = (Spinner) findViewById(R.id.spnChooseAccount);

		/*
		 * Assigning the adapter to a spinner so that spinner shows arraylist of
		 * strings
		 */
		spnChooseAccount.setAdapter(adapter);

		btnOpenAccount = (Button) findViewById(R.id.btnOpenAccount);
		btnOpenAccount.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				/*
				 * Check for if the database does not exist go directly go to
				 * front screen
				 */
				if (Utils.databaseDoesNotExist(getApplicationContext())) {
					Intent intent1 = new Intent(ChooseAccount.this,
							FrontScreen.class);
					startActivity(intent1);
					return;
				}

				SessionClass.sessionObject().setTitle(
						spnChooseAccount.getSelectedItem().toString());
				Intent intent = new Intent(ChooseAccount.this, Purpose.class);
				startActivity(intent);
			}
		});

		deleteAccount = (Button) findViewById(R.id.deleteAccount);
		deleteAccount.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				/*
				 * Check for if the database does not exist go directly go to
				 * front screen
				 */
				if (Utils.databaseDoesNotExist(getApplicationContext())) {
					Intent intent1 = new Intent(ChooseAccount.this,
							FrontScreen.class);
					startActivity(intent1);
					return;
				}

				showDialogBoxDeleteAccount("Delete Account",
						"Do you want to delete the Account?");
			}
		});

		/* Initialising the open Account statistic button */
		openAccountstatistics = (Button) findViewById(R.id.openAccountStatistics);
		openAccountstatistics.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				/*
				 * Check for if the database does not exist go directly go to
				 * front screen
				 */
				if (Utils.databaseDoesNotExist(getApplicationContext())) {
					Intent intent1 = new Intent(ChooseAccount.this,
							FrontScreen.class);
					startActivity(intent1);
					return;
				}

				SessionClass.sessionObject().setTitle(
						spnChooseAccount.getSelectedItem().toString());
				Intent intent = new Intent(ChooseAccount.this,
						OpenAccountStatistics.class);
				startActivity(intent);
			}
		});

		btnEditAccount = (Button) findViewById(R.id.btnEditAccount);
		btnEditAccount.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				/*
				 * Check for if the database does not exist go directly go to
				 * front screen
				 */
				if (Utils.databaseDoesNotExist(getApplicationContext())) {
					Intent intent1 = new Intent(ChooseAccount.this,
							FrontScreen.class);
					startActivity(intent1);
					return;
				}

				/* Setting the session */
				SessionClass.sessionObject().setTitle(
						spnChooseAccount.getSelectedItem().toString());
				/* Creating the intent to go to another activity */
				Intent intent = new Intent(ChooseAccount.this,
						EditAccount.class);
				startActivity(intent);
			}
		});

		btnRenameAccount = (Button) findViewById(R.id.btnRenameAccount);
		btnRenameAccount.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				/*
				 * Check for if the database does not exist go directly go to
				 * front screen
				 */
				if (Utils.databaseDoesNotExist(getApplicationContext())) {
					Intent intent1 = new Intent(ChooseAccount.this,
							FrontScreen.class);
					startActivity(intent1);
					return;
				}

				showDialogBoxRenameAccount("Rename the Account",
						"Enter the account name");
			}
		});

	}

	/* Dialog box for Renaming a member */
	private void showDialogBoxRenameAccount(String title, String message) {

		/* Creating object to access its methods */
		databaseOperations = new DatabaseOperations(getApplicationContext());

		/* Firstly we create an object of AlertDialog.Builder */
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
		/* Now we initialise its contents */
		dialogBuilder.setTitle(title);
		dialogBuilder.setMessage(message);

		input = new EditText(this);
		input.setSingleLine();
		input.setText(spnChooseAccount.getSelectedItem().toString());
		/* Function to put the cursor at the last */
		Utils.setCursorPosition(input);
		dialogBuilder.setView(input);

		/* Adding a event for changing text */
		input.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				Utils.validateTextLength(input);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		dialogBuilder.setPositiveButton("Rename",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {

						/* Inserting the record */
						databaseOperations.openWriteableDatabase();

						/*
						 * Validation for checking if the renamed account is
						 * there or not
						 */
						if (databaseOperations.retrieve(DatabaseOperations
								.getAmounttable(),
								new String[] { DatabaseOperations
										.getAmounttabletitle() },
								DatabaseOperations.getAmounttabletitle()
										+ "=\""
										+ input.getText().toString()
												.replaceAll("\\s+", " ").trim()
										+ "\"", null, null, null, null) != null) {
							Toast.makeText(getApplicationContext(),
									"Unable to rename, account already exists",
									Toast.LENGTH_SHORT).show();
							databaseOperations.closeDatabase();
							return;
						}

						/*
						 * Renaming the title in the amount table and that will
						 * cascade everywhere as it is having on update cascade
						 * constraint
						 */
						/* Pop up to say that account was renamed */
						Toast.makeText(
								getApplicationContext(),
								spnChooseAccount.getSelectedItem().toString()
										+ " was renamed to "
										+ input.getText().toString()
												.replaceAll("\\s+", " ").trim(),
								Toast.LENGTH_SHORT).show();

						databaseOperations.updateRow(
								DatabaseOperations.getAmounttable(),
								DatabaseOperations.getAmounttabletitle(),
								input.getText().toString()
										.replaceAll("\\s+", " ").trim(),
								DatabaseOperations.getAmounttabletitle()
										+ "=\""
										+ spnChooseAccount.getSelectedItem()
												.toString() + "\"", null);

						/* Code to get all the accounts from the database */
						titles = databaseOperations.retrieveAll(
								DatabaseOperations.getAmounttable(),
								new String[] { DatabaseOperations
										.getAmounttabletitle() }, null, null,
								null, null, null);

						/* Initialising the adapter */
						adapter = new ArrayAdapter<String>(
								getApplicationContext(),
								android.R.layout.simple_spinner_item, titles);

						/*
						 * Assigning the adapter to a spinner so that spinner
						 * shows arraylist of strings
						 */
						spnChooseAccount.setAdapter(adapter);

						/* Closing the database */
						databaseOperations.closeDatabase();

					}
				});

		dialogBuilder.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						return;
					}
				});

		AlertDialog alertDialog = dialogBuilder.create();
		alertDialog.show();
	}

	/* Dialog box for confirmation for deleting an account */
	private void showDialogBoxDeleteAccount(String title, String message) {
		/* Firstly we create an object of AlertDialog.Builder */
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
		/* Now we initialise its contents */
		dialogBuilder.setTitle(title);
		dialogBuilder.setMessage(message);
		dialogBuilder.setPositiveButton("Yes",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						/* Code to open the database */
						databaseOperations.openWriteableDatabase();

						/* Pop up for showing that account deleted */
						Toast.makeText(
								getApplicationContext(),
								"Account "
										+ spnChooseAccount.getSelectedItem()
												.toString()
										+ " has been deleted",
								Toast.LENGTH_SHORT).show();

						@SuppressWarnings("unused")
						int x = databaseOperations.deleteRow(
								DatabaseOperations.getAmounttable(),
								DatabaseOperations.getAmounttabletitle()
										+ "="
										+ "\""
										+ spnChooseAccount.getSelectedItem()
												.toString() + "\"", null);

						/* Code to get all the accounts from the database */
						titles = databaseOperations.retrieveAll(
								DatabaseOperations.getAmounttable(),
								new String[] { DatabaseOperations
										.getAmounttabletitle() }, null, null,
								null, null, null);

						/* Initialising the adapter */
						adapter = new ArrayAdapter<String>(
								getApplicationContext(),
								android.R.layout.simple_spinner_item, titles);

						spnChooseAccount.setAdapter(adapter);

						if (titles.size() == 0) {
							Toast.makeText(getApplicationContext(),
									"No Account to open", Toast.LENGTH_SHORT)
									.show();
							/* Code to close the database */
							databaseOperations.closeDatabase();
							finish();
							return;
						}

						/* Code to close the database */
						databaseOperations.closeDatabase();
					}
				});

		dialogBuilder.setNegativeButton("No",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						return;
					}
				});

		AlertDialog alertDialog = dialogBuilder.create();
		alertDialog.show();
	}

}
